import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { editUser, getCurrentUser } from "@/api/user";

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter();
  const loginModalRef = ref();
  const profileModalRef = ref();
  const isEditing = ref(false);
  const formState = ref({
    userName: ''
  });

  // 用户信息
  const user = ref<any>({
    user: "未登录",
    userId: null,
    userName: null
  });

  // 远程获取登录信息
  const fetchLoginUser = async () => {
    const res = await getCurrentUser();
    if (res.data.code === 200 && res.data.data) {
      user.value = res.data.data;
    }
  };

  // 检查是否登录
  const checkLogin = () => {
    if (!user.value.userId) {
      showLoginModal();
      return false;
    }
    return true;
  };

  // 显示登录弹窗
  const showLoginModal = () => {
    loginModalRef.value?.show();
  };

  // 显示个人信息弹窗
  const showProfileModal = () => {
    if (!checkLogin()) return;
    profileModalRef.value?.showModal();
    isEditing.value = false;
    formState.value.userName = user.value.userName || '';
  };

  // 处理编辑个人信息
  const handleEditProfile = () => {
    if (!checkLogin()) return;
    isEditing.value = true;
  };

  // 处理保存个人信息
  const handleSaveProfile = async () => {
    if (!checkLogin()) return;
    try {
      const res = await editUser({
        userName: formState.value.userName
      });

      if (res.data.code === 200) {
        user.value.userName = formState.value.userName;
        message.success('保存成功');
        isEditing.value = false;
      } else {
        message.error(res.data.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存个人信息失败:', error);
      message.error('保存失败，请稍后重试');
    }
  };

  // 处理退出登录
  const handleLogout = () => {
    localStorage.removeItem('token');
    user.value = {
      user: "未登录",
      userId: null,
      userName: null
    };
    router.push('/order');
  };

  // 设置用户信息
  const setUser = (userData: any) => {
    user.value = userData;
  };

  return {
    user,
    loginModalRef,
    profileModalRef,
    isEditing,
    formState,
    checkLogin,
    showLoginModal,
    showProfileModal,
    handleEditProfile,
    handleSaveProfile,
    handleLogout,
    setUser,
    fetchLoginUser
  };
}); 